package com.mmall.common;

import com.mmall.exception.ParamException;
import com.mmall.exception.PermissionException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author wangtengyu
 * @Create 2018-03-05-16:47
 * 全局异常类
 */
@Component
@Slf4j
public class ExceptionResolver implements HandlerExceptionResolver {
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object, Exception ex) {
        String url=httpServletRequest.getRequestURL().toString();
        ModelAndView modelAndView;
        String defaultMsg="System error";
        //这里要求json请求都用.json结果
        if(url.endsWith(".json")){
            if(ex instanceof ParamException ||ex instanceof PermissionException ||ex instanceof NullPointerException){
                ServerResponse serverResponse=ServerResponse.createByErrorMessage(ex.getMessage());
                modelAndView=new ModelAndView("jsonView",this.toMap(serverResponse));
            }else {
                log.error("unknow json exception url {}",url,ex);
                ServerResponse serverResponse=ServerResponse.createByErrorMessage(defaultMsg);
                modelAndView=new ModelAndView("jsonView",this.toMap(serverResponse));
            }
        }else if (url.endsWith(".page")){
            log.error("unknow exception url{}",url,ex);
            ServerResponse serverResponse=ServerResponse.createByErrorMessage(defaultMsg);
            modelAndView=new ModelAndView("jsonView",this.toMap(serverResponse));
        }else {
            log.error("unknow exception url {}",url,ex);
            ServerResponse serverResponse=ServerResponse.createByErrorMessage(defaultMsg);
            modelAndView=new ModelAndView("jsonView",this.toMap(serverResponse));
        }
        return  modelAndView;
    }




    public Map<String,Object> toMap(ServerResponse serverResponse){
        HashMap<String,Object> map=new HashMap<String, Object>();
        map.put("status",serverResponse.isStatus());
        map.put("msg",serverResponse.getMsg());
        map.put("data",serverResponse.getData());
        return map;
    }






}
